import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket=null;
    private String serverIP;
    private int serverPort;
    //UDP本身不保存客户端的信息，所以自己保存一下。
    //和服务器不一样这里需要自己指定一下服务器的地址
    public UdpEchoClient (String serverIP, int serverPort) throws SocketException {
        this.serverIP=serverIP;
        this.serverPort=serverPort;
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while (true){
            System.out.println("请输入要发送的内容");
            if (!scanner.hasNext()){
                break;
            }
            String request=scanner.next();
            DatagramPacket requestPAcket=new DatagramPacket(request.getBytes(),request.getBytes().length
            , InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPAcket);
            DatagramPacket resposePacket=new DatagramPacket(new byte[4090],4090);
            socket.receive(resposePacket);
            String respose=new String(resposePacket.getData(),0,resposePacket.getLength());
            System.out.println(respose);
        }

    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
